package cn.lblbc.todo

import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

class AddEditTaskActivity : AppCompatActivity() {
    private var task: Task? = null
    private lateinit var calendar: Calendar
    private lateinit var titleInputLayout: TextInputLayout
    private lateinit var titleEditText: TextInputEditText
    private lateinit var descriptionInputLayout: TextInputLayout
    private lateinit var descriptionEditText: TextInputEditText
    private lateinit var dateInputLayout: TextInputLayout
    private lateinit var dateEditText: TextInputEditText
    private lateinit var timeInputLayout: TextInputLayout
    private lateinit var timeEditText: TextInputEditText
    private var saveMenuItem: MenuItem? = null
    private var isDateAndTimeSet = false
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_edit_task)
        
        // 初始化日历
        calendar = Calendar.getInstance()
        
        // 检查是否是编辑模式
        task = intent.getSerializableExtra(MainActivity.EXTRA_TASK) as Task?
        
        // 设置工具栏
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        
        // 设置标题
        if (task == null) {
            supportActionBar?.title = "添加新任务"
        } else {
            supportActionBar?.title = "编辑任务"
        }
        
        // 初始化视图
        initViews()
    }
    
    private fun initViews() {
        titleInputLayout = findViewById(R.id.titleInputLayout)
        titleEditText = findViewById(R.id.titleEditText)
        descriptionInputLayout = findViewById(R.id.descriptionInputLayout)
        descriptionEditText = findViewById(R.id.descriptionEditText)
        dateInputLayout = findViewById(R.id.dateInputLayout)
        dateEditText = findViewById(R.id.dateEditText)
        timeInputLayout = findViewById(R.id.timeInputLayout)
        timeEditText = findViewById(R.id.timeEditText)
        
        // 如果是编辑模式，填充现有数据
        task?.let {
            titleEditText.setText(it.title)
            descriptionEditText.setText(it.description)
            it.dueDate?.let { dueDate ->
                calendar.time = dueDate
                updateDateAndTimeText()
                isDateAndTimeSet = true
            }
        }
        // 如果是新增模式，默认不设置日期和时间
        if (task == null) {
            dateEditText.setText("")
            timeEditText.setText("")
            isDateAndTimeSet = false
        }
        
        // 设置日期选择器
        dateEditText.setOnClickListener {
            showDatePicker()
        }
        
        // 设置时间选择器
        timeEditText.setOnClickListener {
            if (!isDateAndTimeSet) {
                // 如果还没有设置日期时间，先设置为当前时间
                updateDateAndTimeText()
                isDateAndTimeSet = true
            }
            showTimePicker()
        }
        
        // 更新保存按钮状态
        titleEditText.addTextChangedListener(object : android.text.TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: android.text.Editable?) {
                updateSaveButtonState()
            }
        })
        
        // 初始化保存按钮状态
        updateSaveButtonState()
    }
    
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        return if (task == null) {
            // 添加新任务时显示保存按钮
            menuInflater.inflate(R.menu.add_task_menu, menu)
            saveMenuItem = menu.findItem(R.id.action_save)
            updateSaveButtonState()
            true
        } else {
            // 编辑任务时显示三个点菜单
            menuInflater.inflate(R.menu.edit_task_menu, menu)
            saveMenuItem = menu.findItem(R.id.action_save)
            true
        }
    }
    
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            android.R.id.home -> {
                onBackPressed()
                true
            }
            R.id.action_save -> {
                saveTask()
                true
            }
            R.id.action_delete -> {
                deleteTask()
                true
            }
            R.id.action_complete -> {
                completeTask()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    
    private fun showDatePicker() {
        val datePickerDialog = DatePickerDialog(
            this,
            { _, year, month, dayOfMonth ->
                calendar.set(Calendar.YEAR, year)
                calendar.set(Calendar.MONTH, month)
                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                updateDateAndTimeText()
                isDateAndTimeSet = true
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        )
        datePickerDialog.show()
    }
    
    private fun showTimePicker() {
        val timePickerDialog = TimePickerDialog(
            this,
            { _, hourOfDay, minute ->
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
                calendar.set(Calendar.MINUTE, minute)
                updateDateAndTimeText()
            },
            calendar.get(Calendar.HOUR_OF_DAY),
            calendar.get(Calendar.MINUTE),
            true
        )
        timePickerDialog.show()
    }
    
    private fun updateDateAndTimeText() {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val timeFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
        dateEditText.setText(dateFormat.format(calendar.time))
        timeEditText.setText(timeFormat.format(calendar.time))
    }
    
    private fun updateSaveButtonState() {
        if (task == null) {
            val isTitleEmpty = titleEditText.text.isNullOrEmpty()
            saveMenuItem?.isEnabled = !isTitleEmpty
        }
    }
    
    private fun saveTask() {
        val title = titleEditText.text.toString()
        val description = descriptionEditText.text.toString()
        
        if (title.isEmpty()) {
            titleInputLayout.error = "任务标题不能为空"
            Toast.makeText(this, "请输入任务标题", Toast.LENGTH_SHORT).show()
            return
        } else {
            titleInputLayout.error = null
        }
        
        // 保存任务逻辑
        if (task == null) {
            // 添加新任务
            val newTask = if (isDateAndTimeSet) {
                Task(
                    title = title,
                    description = description,
                    dueDate = calendar.time
                )
            } else {
                Task(
                    title = title,
                    description = description
                )
            }
            TaskManager.addTask(newTask)
            Toast.makeText(this, "任务已添加", Toast.LENGTH_SHORT).show()
        } else {
            // 更新现有任务
            task?.title = title
            task?.description = description
            task?.dueDate = if (isDateAndTimeSet) calendar.time else null
            task?.let { TaskManager.updateTask(it) }
            Toast.makeText(this, "任务已更新", Toast.LENGTH_SHORT).show()
        }
        
        // 设置结果并返回主界面
        setResult(RESULT_OK)
        finish() // 返回主界面
    }
    
    private fun deleteTask() {
        task?.let {
            TaskManager.deleteTask(it.id)
            Toast.makeText(this, "任务已删除", Toast.LENGTH_SHORT).show()
            setResult(RESULT_OK)
            finish()
        }
    }
    
    private fun completeTask() {
        task?.let {
            it.isCompleted = true
            TaskManager.updateTask(it)
            Toast.makeText(this, "任务已完成", Toast.LENGTH_SHORT).show()
            setResult(RESULT_OK)
            finish()
        }
    }
}